package ru.compscicenter.databases.zaikina.common.model;

import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Document implements JSONAware, Cloneable {
    private final Integer id;
    private final String title;

    public Document(Integer id, String title) {
        this.id = id;
        this.title = title;
    }

    public Integer getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String toJSONString() {
        JSONObject obj = new JSONObject();
        obj.put("id", id);
        obj.put("title", title);
        return obj.toString();
    }

    public static Document parse(String jsonString) {
        String title;
        Integer id;
        try {
            JSONObject obj = (JSONObject) JSONValue.parse(jsonString);
            title = obj.get("title").toString();
            String value = obj.get("id").toString();
            id = Integer.parseInt(value);
        } catch (Exception ex) {
            return null;
        }
        return new Document(id, title);
    }

    public Document clone() {
        return new Document(new Integer(id.intValue()), new String(title));
    }

    public boolean equals(Object obj) {
        if (obj instanceof Document) {
            Document doc = (Document) obj;
            return doc.id.equals(id) && doc.title.equals(title);
        }
        return false;
    }
}
